<?php

class Block extends CWidget {
	
	public $title = 'title';
	public $links = array();
	
	protected $_defaultHtmlOptions = array(
		'class' => 'block',
	);		
	public $htmlOptions = array();
	
	
	protected function getHtmlOptions() {
		$merged = array_merge($this->_defaultHtmlOptions, $this->htmlOptions);
		if(isset($this->htmlOptions['class'])) {
			$merged['class'] = 
				$this->_defaultHtmlOptions['class'] . ' ' . $this->htmlOptions['class'];
		}
		$merged['id'] = isset($merged['id']) ? $merged['id'] : $this->id;
		return $merged;
	}
	
	protected function createLinks($links) {
		$lks = array();
		foreach($links as $text => $link) {
			$link['class'] = 'BlockLinker';
			$link['text'] = $text;
			$lks[] = Yii::createComponent($link);
		}
		return $lks;
	}
	
	protected function getLinkHtml() {
		$links = $this->createLinks($this->links);
		$html = '<ul class="ops">';
		foreach($links as $index => $link) {
			$html .= $index == 1 ? '<li class="nobg">' : '<li>'; 
			$html .= $link->generate();
			$html .= '</li>';
		}
		$html .= '</ul>';
		return $html;
	}
	
	public function resolveTitle() {
		$title = $this->title;
		if(is_string($title)) {
			return "<h2>{$title}</h2>";
		} else {
			$html = "<div><ul id='{$this->id}-nav' class='tabs'>";
			foreach($title as $id=>$label) {
				$html .= "<li><a href='#{$id}'>{$label}</a></li>";
			}
			$html .= '</ul></div>';
			Yii::app()->clientScript->registerScript($this->id.'-tab', "
				var tabber2 = new Yetii({
					id: '{$this->id}'
				});
			");
			return $html;
		}
	}
	
	public function init() {
	
		$openTag = CHtml::openTag('div', $this->getHtmlOptions());
		$title = $this->resolveTitle();
		
		$html = <<<EOD
$openTag
	<div class="block_head">
		<div class="bheadl"></div>
		<div class="bheadr"></div>
		<h2>{$title}</h2>
		{$this->linkHtml}
	</div>		<!-- .block_head ends -->
	<div class="block_content">
EOD;

		echo $html;
	}
	
	public function run() {
		$html = <<<EOD
</div>		<!-- .block_content ends -->
	<div class="bendl"></div>
	<div class="bendr"></div>
</div>
EOD;
	
		echo $html;
	}

}

class BlockLinker extends CComponent {
	
	public $url = '';
	public $text = '';
	public $htmlOptions = array();

	public function generate() {
		return CHtml::link($this->text, $this->url, $this->htmlOptions);
	}
	
	
}

?>